// home_spk/pages/goods_list/index.js
import { throttle } from 'miniprogram-licia'
Page({
  data: {
    hasMore: true,
    goodsList: [],
    scrollTop: 0,
    backTopShow: false,
  },
  onLoad({ query }) {
    this.getGoodsList(query)
    this.getMoreGoods = throttle(() => {
      if (!this.data.hasMore) return
      this.getGoodsList(query, ++this._pagenum)
    }, 100)
  },
  async getGoodsList(query, pagenum = 1, pagesize = 10) {
    const { message, meta } = await wx.http.get('/api/public/v1/goods/search', {
      query,
      pagenum,
      pagesize
    })
    if (meta.status !== 200) wx.utils.toast('获取商品列表失败！')
    this.setData({
      hasMore: this.data.goodsList.length < message.total,
      goodsList: this.data.goodsList.concat(message.goods)
    })
    this._pagenum = pagenum
  },
  scroll({ detail }) {
    if (detail.scrollTop >= 300 && !this.data.backTopShow) {
      this.setData({
        backTopShow: true
      })
    }
    if (detail.scrollTop < 300 && this.data.backTopShow) {
      this.setData({
        backTopShow: false
      })
    }
  },
  backTop() {
    this.setData({
      scrollTop: 0
    })
  },
  goDetail(ev) {
    wx.navigateTo({
      url: '/home_spk/pages/goods_detail/index?goods_id=' + ev.mark.id,
    })
  }
})